package org.cheetah.spring.xml;

import java.util.List;

import org.cheetah.spring.xml.factory.IfProcessorFactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class IfDefinitionParser extends AbstractSingleBeanDefinitionParser {

	@Override
	protected Class<?> getBeanClass(Element element) {
		return IfProcessorFactoryBean.class;
	}

	@Override
	protected void doParse(Element element, ParserContext context,
			BeanDefinitionBuilder bean) {
		String condition = element.getAttribute("condition");
		String predicate = element.getAttribute("predicate");

		List<Object> then = new ManagedList<Object>();
		List<Object> _else = new ManagedList<Object>();

		NodeList nodeList = element.getChildNodes();
		int count = nodeList.getLength();

		boolean thenMode = true;
		boolean elseMode = false;

		for (int i = 0; i < count; ++i) {
			Node node = nodeList.item(i);

			if (Element.class.isInstance(node)) {
				Element child = (Element) node;

				if ("else".equals(child.getLocalName())) {
					thenMode = false;
					elseMode = true;
				} else {
					Object obj = context.getDelegate().parsePropertySubElement(
							child, bean.getRawBeanDefinition());

					if (thenMode) {
						then.add(obj);
					} else if (elseMode) {
						_else.add(obj);
					}
				}
			}
		}

		if (StringUtils.hasText(condition)) {
			bean.addPropertyValue("condition", condition);
		}
		if (StringUtils.hasText(predicate)) {
			bean.addPropertyReference("predicate", predicate);
		}

		bean.addPropertyValue("then", then);
		bean.addPropertyValue("else", _else);
	}
}
